// pages/order-detail/order-detail.js
const request = require('../../utils/request');

Page({
  data: {
    orderNo: '',
    order: null,
    loading: true
  },

  onLoad(options) {
    if (options.orderNo) {
      this.setData({ orderNo: options.orderNo });
      this.loadOrderDetail();
    }
  },

  onShow() {
    // 从支付页面返回时刷新订单详情
    if (this.data.orderNo) {
      this.loadOrderDetail();
    }
  },

  // 加载订单详情
  async loadOrderDetail() {
    try {
      const res = await request.get(`/orders/${this.data.orderNo}`);

      if (res.success) {
        const order = res.data;
        
        // 解析规格信息
        if (order.spec_info) {
          try {
            order.specInfoParsed = JSON.parse(order.spec_info);
          } catch (e) {
            order.specInfoParsed = null;
          }
        }
        
        this.setData({
          order: order,
          loading: false
        });
      } else {
        wx.showToast({
          title: res.message || '加载失败',
          icon: 'none'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      }
    } catch (error) {
      console.error('加载订单详情失败:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 复制订单号
  copyOrderNo() {
    wx.setClipboardData({
      data: this.data.orderNo,
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'success'
        });
      }
    });
  },

  // 复制下载地址
  copyDownloadUrl(e) {
    const url = e.currentTarget.dataset.url;
    if (!url) return;
    
    wx.setClipboardData({
      data: url,
      success: () => {
        wx.showToast({
          title: '链接已复制',
          icon: 'success'
        });
      }
    });
  },

  // 打开下载地址
  openDownloadUrl(e) {
    const url = e.currentTarget.dataset.url;
    if (!url) return;
    
    wx.showModal({
      title: '提示',
      content: '即将打开下载链接，请在浏览器中查看',
      confirmText: '打开',
      success: (res) => {
        if (res.confirm) {
          // 小程序无法直接打开外部链接，提示用户复制后打开
          wx.setClipboardData({
            data: url,
            success: () => {
              wx.showModal({
                title: '链接已复制',
                content: '链接已复制到剪贴板，请粘贴到浏览器中打开',
                showCancel: false
              });
            }
          });
        }
      }
    });
  },

  // 跳转到评价页面
  goToReview() {
    const { order } = this.data;
    if (!order) return;
    
    wx.navigateTo({
      url: `/pages/review/review?productId=${order.product_id}&orderNo=${order.order_no}&productName=${order.product_name}`
    });
  },

  // 查询支付状态
  async queryPayment() {
    wx.showLoading({ title: '查询中...' });

    try {
      const res = await request.get(`/pay/query/${this.data.orderNo}`);
      wx.hideLoading();

      if (res.success) {
        const { tradeState, tradeStateDesc } = res.data;
        
        if (tradeState === 'SUCCESS') {
          wx.showToast({
            title: '支付成功',
            icon: 'success'
          });
          // 延迟一下再刷新订单详情，确保后端已经处理完发货
          setTimeout(() => {
            this.loadOrderDetail();
          }, 1000);
        } else {
          wx.showModal({
            title: '支付状态',
            content: tradeStateDesc,
            showCancel: false
          });
        }
      } else {
        wx.showToast({
          title: res.message || '查询失败',
          icon: 'none'
        });
      }
    } catch (error) {
      wx.hideLoading();
      console.error('查询支付失败:', error);
      wx.showToast({
        title: '网络错误',
        icon: 'none'
      });
    }
  }
});


